package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    SpuInfoMapper spuInfoMapper;

    @Autowired
    BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    SpuImageMapper spuImageMapper;

    @Autowired
    SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    SkuInfoMapper skuInfoMapper;

    @Autowired
    SkuImageMapper skuImageMapper;

    @Autowired
    SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitService rabbitService;

    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        QueryWrapper<BaseCategory2> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category1_id",category1Id);
        return baseCategory2Mapper.selectList(queryWrapper);
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        QueryWrapper<BaseCategory3> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category2_id",category2Id);
        return baseCategory3Mapper.selectList(queryWrapper);
    }

    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {

        List<BaseAttrInfo> list =  baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);
        return list;
    }

    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //平台属性表
        baseAttrInfoMapper.insert(baseAttrInfo);
        //平台属性值表
        List<BaseAttrValue> list = baseAttrInfo.getAttrValueList();
        if (list != null && list.size()> 0){
            list.forEach(baseAttrValue -> {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            });
        }
    }

    @Override
    public IPage baseTrademark(Integer page, Integer limit) {

        IPage<BaseTrademark> baseTrademarkIPage = baseTrademarkMapper.selectPage(new Page<>(page, limit), null);
        return baseTrademarkIPage;
    }

    @Override
    public IPage findSpuList(Integer page, Integer limit, Long category3Id) {

        return spuInfoMapper.selectPage(new Page<>(page,limit),new QueryWrapper<SpuInfo>().eq("category3_id",category3Id));
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
        List<BaseTrademark> baseTrademarkIPage = baseTrademarkMapper.selectList(null);
        return baseTrademarkIPage;
    }

    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //添加SpuInfo表
        spuInfoMapper.insert(spuInfo);
        //添加SpuImage表
        spuInfo.getSpuImageList().forEach(spuImage -> {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        //添加SpuSaleAttr表
        spuInfo.getSpuSaleAttrList().forEach(spuSaleAttr -> {
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //添加SpuSaleAttrValue表
            spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        List<BaseSaleAttr> list = baseSaleAttrMapper.selectList(null);
        return list;
    }

    @Override
    public List<SpuImage> spuImageList(Long spuId) {

        List<SpuImage> list = spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id",spuId));
        return list;
    }

    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {

        List<SpuSaleAttr> list = spuSaleAttrMapper.spuSaleAttrList(spuId);
        return list;
    }

    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {

        skuInfo.setIsSale(SkuInfo.NOSALE);
        //添加sku表
        skuInfoMapper.insert(skuInfo);
        //添加skuAttrValue表
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //添加skuSaleAttrValue表
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
        //添加skuImage表
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {

        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id",attrId));
    }

    @Override
    public IPage skuList(Integer page, Integer limit) {

        IPage<SkuInfo> skuInfoIPage = skuInfoMapper.selectPage(new Page<>(page,limit), null);
        return skuInfoIPage;
    }

    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);
        skuInfoMapper.updateById(skuInfo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }


    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.updateById(skuInfo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    @Override
    @GmallCache(prefix = RedisConst.SKUKEY_PREFIX)
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        /*//查询缓存
        String cacheKey = RedisConst.SKUKEY_PREFIX+category3Id+RedisConst.SKUKEY_SUFFIX;
        BaseCategoryView baseCategoryView = (BaseCategoryView) redisTemplate.opsForValue().get(cacheKey);
        if(baseCategoryView != null){
            return baseCategoryView;
        }else {
            //查询数据库&&解决缓存击穿
            String cacheLockKey = RedisConst.SKUKEY_PREFIX+category3Id+RedisConst.SKULOCK_SUFFIX;
            String uuid = UUID.randomUUID().toString();
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey, uuid, 2, TimeUnit.SECONDS);
            if (lock){
                baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
                if (baseCategoryView != null){
                    //解决缓存雪崩
                    redisTemplate.opsForValue().set(cacheKey,baseCategoryView,RedisConst.SKUKEY_TIMEOUT+new Random().nextInt(300),TimeUnit.SECONDS);
                    //释放锁
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);
                }else {
                    //解决缓存穿透
                    baseCategoryView = new BaseCategoryView();
                    redisTemplate.opsForValue().set(cacheKey,baseCategoryView,5,TimeUnit.MINUTES);
                }
            }else {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return (BaseCategoryView) redisTemplate.opsForValue().get(cacheKey);
            }
        }*/
        return baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    @GmallCache
    public SkuInfo getSkuInfo(Long skuId) {
        /*//查询缓存
        String cacheKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        //缓存有值
        if (skuInfo != null){
            return skuInfo;
        }else {
            //解决缓存击穿
            String cacheLockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            try {
                boolean tryLock = lock.tryLock(1, 2, TimeUnit.SECONDS);
                if (tryLock){
                    try {
                        skuInfo = skuInfoMapper.selectById(skuId);
                        //解决缓存击穿
                        if (skuInfo != null){
                            List<SkuImage> skuImages = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
                            skuInfo.setSkuImageList(skuImages);
                            //解决缓存雪崩
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,RedisConst.SKUKEY_TIMEOUT+new Random().nextInt(300), TimeUnit.SECONDS);
                        }else {
                            skuInfo = new SkuInfo();
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,300,TimeUnit.SECONDS);
                        }
                    } finally {
                        lock.unlock();
                    }
                }else {
                    TimeUnit.SECONDS.sleep(2);
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/
        SkuInfo skuInfo=skuInfoMapper.selectById(skuId);
        List<SkuImage> skuImages = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
        skuInfo.setSkuImageList(skuImages);
        return  skuInfo;
    }

    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        return skuInfo.getPrice();
    }

    @Override
    @GmallCache(prefix = RedisConst.SKUKEY_PREFIX)
    public List<SpuSaleAttr> getSaleAttrAndValeAndChecked(Long skuId, Long spuId) {
        /*//查询缓存
        String  cacheKey = RedisConst.SKUKEY_PREFIX+skuId+spuId+RedisConst.SKUKEY_SUFFIX;
        List<SpuSaleAttr> saleAttrAndValeAndChecked = (List<SpuSaleAttr>) redisTemplate.opsForValue().get(cacheKey);
        if (saleAttrAndValeAndChecked != null){
            return saleAttrAndValeAndChecked;
        }else {
            //解决缓存击穿
            String cacheLockKey = RedisConst.SKUKEY_PREFIX+skuId+spuId+RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            try {
                boolean tryLock = lock.tryLock(1, 2, TimeUnit.SECONDS);
                if (tryLock){
                    try {
                        saleAttrAndValeAndChecked = spuSaleAttrMapper.getSaleAttrAndValeAndChecked(skuId, spuId);
                        if (saleAttrAndValeAndChecked != null){
                            //解决缓存雪崩
                            redisTemplate.opsForValue().set(cacheKey,saleAttrAndValeAndChecked,RedisConst.SKUKEY_TIMEOUT+new Random().nextInt(300),TimeUnit.SECONDS);
                        }else {
                            //解决穿透
                            saleAttrAndValeAndChecked = new ArrayList<>();
                            redisTemplate.opsForValue().set(cacheKey,saleAttrAndValeAndChecked,300,TimeUnit.SECONDS);
                        }
                    } finally {
                        lock.unlock();
                    }
                }else {
                    TimeUnit.SECONDS.sleep(2);
                    saleAttrAndValeAndChecked = (List<SpuSaleAttr>) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/
        return  spuSaleAttrMapper.getSaleAttrAndValeAndChecked(skuId, spuId);
    }

    @GmallCache(prefix = RedisConst.SKUKEY_PREFIX)
    @Override
    public Map<String, String> getSkuValueIdsMap(Long spuId) {
        List<Map<String,Object>> ListMap = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map<String, String> result = new HashMap<>();
        ListMap.forEach(map -> {
            result.put(String.valueOf(map.get("value_ids")),String.valueOf(map.get("sku_id")));
        });
        return result;
    }

    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {

        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {

        return baseTrademarkMapper.selectById(tmId);
    }

    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {

        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }
}
